﻿using AutoMapper;
using MediatR;
using MyRabbit.Application.Command.ImmuneCommand;
using MyRabbit.Application.ErrorCode;
using MyRabbit.Domain;
using MyRabbit.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyRabbit.Application.CommandHandler.ImmuneCommandHandler
{
    public class ImmuneDelCommandHandler : IRequestHandler<ImmuneDelCommand, APIResult<object>>
    {

        /// <summary>
        /// 免疫仓储
        /// </summary>
        private readonly IRepository<Immune> ImmRep;
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="immRep"></param>
        /// <param name="mapper"></param>
        public ImmuneDelCommandHandler(IRepository<Immune> immRep, IMapper mapper)
        {
            ImmRep = immRep;
            this.mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(ImmuneDelCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();

            try
            {
                // 根据ID获取免疫信息
                Immune immune = await ImmRep.GetByIdAsync(request.ImmuneId);

                if (immune == null)
                {
                    // 如果免疫信息不存在，返回错误状态和消息
                    result.Code = Codes.删除失败;
                    result.Message = Codes.删除失败 + "免疫信息不存在";
                }
                else
                {
                    // 删除免疫信息并返回成功状态和消息
                    await ImmRep.DeleteAsync(immune);
                    result.Code = Codes.删除成功;
                    result.Message = Codes.删除成功.ToString();
                }
            }
            catch (Exception ex)
            {
                // 捕获异常并返回错误状态和消息
                result.Code = Codes.删除失败;
                result.Message = Codes.删除失败 + ex.Message;
            }
            // 返回结果
            return await Task.FromResult(result);
        }
    }
}
